<template>  
<view class="container">
	<status-bar bgColor="#4c9bfb"></status-bar>
  <!-- 顶部标题栏 -->
  <view class="nav-bar">
    <view class="nav-title">首页</view>
    <view class="nav-right" @click="callCustomerService">
      <image src="/static/images/icon/customer-phone.png" class="headset-icon"></image>
    </view>
  </view>
  
  <!-- 订单统计卡片 -->
  <view class="order-stats">
    <view class="stat-item" @click="goToTodayOrder">
      <text class="stat-number">{{todayOrderCount}}</text>
      <text class="stat-label">今日订单</text>
    </view>
    <view class="stat-item" @click="goToTomorrowOrder">
      <text class="stat-number">{{tomorrowOrderCount}}</text>
      <text class="stat-label">明日订单</text>
    </view>
    <view class="stat-item" @click="goToAbnormalOrder">
      <text class="stat-number">{{abnormalOrderCount}}</text>
      <text class="stat-label">异常订单</text>
    </view>
  </view>
  
  <!-- 功能按钮区域 -->
  <view class="function-area">
    <view class="function-row">
      <view class="function-item" @click="goToPendingAppointment">
        <view class="function-icon icon-red">
          <uni-icons type="calendar" size="24" color="#FFFFFF"></uni-icons>
        </view>
        <text class="function-text">待预约({{ appointmentPendingCount }})</text>
      </view>
      <view class="function-item" @click="goToPendingService">
        <view class="function-icon icon-green">
          <uni-icons type="star" size="24" color="#FFFFFF"></uni-icons>
        </view>
        <text class="function-text">待服务({{ pendingServiceCount }})</text>
      </view>
      <view class="function-item" @click="goToUrgentOrder">
        <view class="function-icon icon-orange">
          <uni-icons type="plusempty" size="24" color="#FFFFFF"></uni-icons>
        </view>
        <text class="function-text">加急单({{ urgentCount }})</text>
      </view>
    </view>
  </view>

  <!-- 底部占位，防止内容被tabbar遮挡 -->
  <view class="tabbar-placeholder"></view>
  
  <!-- 使用自定义tabbar -->
  <custom-tabbar :active="0"></custom-tabbar>
</view>
</template>
  
<script>
import { indexStatistics } from '@/api/app/master/index.js'
import { customerPhone } from '@/api/app/master/master.js'

export default {
  data() {
    return {
      masterName: this.$store.state.master.masterName,
      todayOrderCount: 0,
      tomorrowOrderCount: 0,
      abnormalOrderCount: 0,

      pendingServiceCount:0,
      appointmentPendingCount:0,
      urgentCount:0,

      customerPhoneNumber: undefined, // 默认客服电话，将被接口返回的数据覆盖

      // 轮询相关
      timer: null,
      pollInterval: 10000 // 轮询间隔（单位：毫秒）
    }
  },
  onLoad() {
    // 加载首页数据
    this.loadIndexData();
    // 获取客服电话
    this.getCustomerPhone();
    // 启动轮询
    this.startIndexPolling();
  },
  onShow(){
  	uni.hideTabBar();
  	this.loadIndexData();
  },
  onHide() {
    // 页面隐藏时停止轮询，避免后台请求
    this.stopIndexPolling();
  },
  onUnload() {
    // 页面卸载时清理轮询
    this.stopIndexPolling();
  },
  methods: {
    // 跳转工作台并默认选中"待预约"
    goToPendingAppointment() {
      // 通过本地存储传递默认选中tab
      uni.setStorageSync('workDefaultTab', 1);
      // TabBar 页面必须使用 switchTab 跳转
      uni.switchTab({
        url: '/pages/index/work'
      });
    },

    // 跳转工作台并默认选中"待服务"
    goToPendingService() {
      uni.setStorageSync('workDefaultTab', 2);
      uni.switchTab({
        url: '/pages/index/work'
      });
    },

    // 加载首页数据
    loadIndexData() {
      indexStatistics().then(res => {
        if (res.code === 200 && res.data) {
          // 更新订单统计数据
          this.todayOrderCount = res.data.todayCount || 0
          this.tomorrowOrderCount = res.data.tomorrowCount || 0
          this.abnormalOrderCount = res.data.abnormalCount || 0
          this.pendingServiceCount=res.data.pendingServiceCount||0
          this.appointmentPendingCount=res.data.appointmentPendingCount||0
          this.urgentCount=res.data.urgentCount||0

        } else {
          console.error('获取首页统计数据失败:', res.msg)
        }
      }).catch(err => {
        console.error('获取首页统计数据异常:', err)
      })
    },
    
    // 跳转到今日订单页面
    goToTodayOrder() {
      uni.navigateTo({
        url: '/pages/order/today-order'
      });
    },
    
    // 跳转到明日订单页面（实际上是跳转到今日订单页面，但加载明日数据）
    goToTomorrowOrder() {
      uni.navigateTo({
        url: '/pages/order/today-order?type=tomorrow'
      });
    },
    
    // 跳转到异常订单页面
    goToAbnormalOrder() {
      uni.navigateTo({
        url: '/pages/order/abnormal-order'
      });
    },

    // 跳转到加急订单页面
    goToUrgentOrder() {
      uni.navigateTo({
        url: '/pages/order/urgent-order'
      });
    },
    
    // 获取客服电话
    getCustomerPhone() {
      customerPhone().then(res => {
        if (res.code === 200 && res.data) {
          // 更新客服电话
          this.customerPhoneNumber = res.data || '';
        } else {
          console.error('获取客服电话失败:', res.msg);
        }
      }).catch(err => {
        console.error('获取客服电话异常:', err);
      });
    },
    
    // 拨打客服电话
    callCustomerService() {
      // 使用从接口获取的客服电话号码
      const phoneNumber = this.customerPhoneNumber;
      // 在这里判断是否有电话，如果没有就返回不进行操作
      if (!phoneNumber) {
        uni.showToast({
          title: '客服电话未配置，请联系管理员',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '联系客服',
        content: `确定要拨打客服电话 ${phoneNumber} 吗？`,
        success: (res) => {
          if (res.confirm) {
            // 用户点击确定，拨打电话
            uni.makePhoneCall({
              phoneNumber: phoneNumber,
              success: () => {
                console.log('拨打电话成功');
              },
              fail: (err) => {
                console.error('拨打电话失败:', err);
                uni.showToast({
                  title: '拨打电话失败',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },

    // 新增：轮询控制
    startIndexPolling() {
      // 避免重复开启
      if (this.timer) return;

      // 启动轮询
      this.timer = setInterval(() => {
        this.loadIndexData();
      }, this.pollInterval);
    },
    stopIndexPolling() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.container {
  padding: 0 0 20rpx 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  background-color: #4c9bfb;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
}

.nav-right {
  position: absolute;
  right: 30rpx;
  display: flex;
  align-items: center;
}

.headset-icon {
  width: 48rpx;
  height: 48rpx;
}

.order-stats {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}

.function-area {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.function-row {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 30rpx;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 33.33%;
}

.function-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10rpx;
}

.icon-red {
  background-color: #ff6b6b;
}

.icon-green {
  background-color: #4cd964;
}

.icon-orange {
  background-color: #ff9500;
}

.icon-purple {
  background-color: #a78bfa;
}

.function-text {
  font-size: 28rpx;
  color: #333;
}

.tabbar-placeholder {
  height: 100rpx;
}
</style>